'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数


	const appid = 'wxa6dc29a3b7a92b1c' //appid
	const secret = '3e41c9372d1843ef8329c1480c7a5405' //secret
	const loginUrl = 'https://api.weixin.qq.com/sns/jscode2session'
	const getAccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token'
	const msgSecCheckUrl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='

	if (event.actionType === 'openid') {
		let js_code = event.code
		let res = await uniCloud.httpclient.request(loginUrl, {
			data: {
				appid: appid,
				secret: secret,
				js_code: js_code,
				grant_type: 'authorization_code'
			},
			dataType: 'json'
		})

		let openid = res.data.openid
		console.log('openid', openid);
		if (openid) {
			return {
				code: 200,
				data: {
					openid
				},
				msg: '获取openid成功'
			}
		} else {
			return {
				code: 201,
				msg: '获取openid失败'
			}
		}
	}

	if (event.actionType === 'msgSecCheck') {
		let access_token = ''
		let res = await uniCloud.httpclient.request(getAccessTokenUrl, {
			data: {
				appid: appid,
				secret: secret,
				grant_type: 'client_credential'
			},
			dataType: 'json'
		})
		if (res.status === 200) {
			access_token = res.data.access_token
			console.log('access_token',access_token);
		} else {
			return {
				code: '201',
				code: '系统异常，请重试',
			}
		}
		let params = {
			// version: 2,
			// openid: event.openid,
			// scene: 3,
			content: event.content
		}

		let result = await uniCloud.httpclient.request(msgSecCheckUrl + access_token, {
			method: 'POST',
			data: params,
			dataType: 'json',
			contentType: 'json'

		})
		console.log(result);
		if (result.status === 200 && result.data.errcode === 0) {
			return {
				code: 200,
				msg: '没有敏感词'
			}
		} else {
			return {
				code: 201,
				msg: '含有敏感词'
			}
		}

	}

};
